package com.rocky.project.tools;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.rocky.project.model.base.BaseEntity;
import com.rocky.project.model.family.Attachment;
import com.rocky.project.model.family.Family;
import com.rocky.project.model.family.Person;
import com.rocky.project.service.BaseService;

/**
 * ArchiveImporter.java create by chen at 2008-11-19 ,上午04:14:30
 * NotMavenTest by ft.comp
 */

/**
 * Archive导入用的工具类
 * 
 * @author chen
 * @version 1.0
 * @since 1.5
 */
public class ArchiveImporterImpl extends BaseDirectoryImporter {
	protected BaseService baseService;
	protected SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private Date now = new Date();
	private String ip = "192.168.0.1";
	// (^[\u4e00-\u9fa5]+)\d*?\.*
	private final String reg = "^([\\u4e00-\\u9fa5]+)\\d*\\.\\S*";
	private Pattern pattern = Pattern.compile(reg);
	private Matcher matcher = null;

	public BaseService getBaseService() {
		return baseService;
	}
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}



	public ArchiveImporterImpl() {
		// 初始化时候取本机IP
		try {
			ip = InetAddress.getLocalHost().getHostAddress();
		} catch (Exception ex) {
			log.info("取本机IP发生错误");
			log.info(ex);
			ip = "127.0.0.1";
		}
	}
	/**
	 * @param user
	 *            初始化一个BaseEntity对象
	 */
	private void initBaseEntity(BaseEntity entity) {
		entity.setCreateIp(ip);		
		entity.setCreator("importer");
		entity.setCreateTime(now);
	}


	private String convertAttType(String type) {
		// 1:photos;//照片 2:pics;//图纸 3:archivePics;//历史档案 4:files;//备注文档
		if ("照片".equals(type)) {
			return "1";
		} else if ("图纸".equals(type)) {
			return "2";
		} else if ("历史档案".equals(type)) {
			return "3";
		} else {
			return "4";
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see BaseDirectoryImporter#parseFile(java.io.File)
	 */
	@Override
	protected void parseFile(File file) throws IOException {
		String name = file.getName();
		matcher = pattern.matcher(name);
		log.info("文件名字为：" + name);
		String area = file.getParentFile().getParentFile().getName();
		log.info("自然村名字为：" + area);
		String attType = file.getParentFile().getName();
		Attachment att;	
		if (matcher.find()) {
			String personName = matcher.group(1);
			log.info("文件中的农民姓名为：" + personName);
			List list = baseService.getHibernateTemplate().find("from Person a where a.name='" + personName + "' and a.area.name like '%" + area + "%'");
			log.info("从数据库查找的匹配的农民信息个数有：" + list.size());
			if (list.size() > 0) {				
				try {
					Person p = (Person) list.get(0);				
					att = new Attachment();
					this.initBaseEntity(att);
					att.setDisplayName(name);
					try {
						Collection fs = baseService.executeHqlNoParam("select m.family from Person m where m.id ='"+p.getId()+"'", 0, null);
						att.setFamily((Family)fs.iterator().next());						
					} catch (Exception e) {
						this.errorCount++;
						this.errors.add("#error#:att.setFamily((Family)fs.iterator().next());");						
					}
					att.setName(name);					
					att.setRelativePath(file.getAbsolutePath());
					att.setSize(file.length());
					att.setType(this.convertAttType(attType));
					this.baseService.create(att);
					this.successCount++;
				} catch (Exception ex) {
					log.info(ex);
					this.errorCount++;
					this.errors.add(file.getCanonicalPath());
				}
			} else {
				this.errorCount++;
				this.errors.add("没有找到该图片对应的农民："+file.getCanonicalPath());
			}
		} else {
			log.info("该文件不包含中文：" + file.getCanonicalPath());
		}
	}
	@Override
	public void beginImport() throws IOException {
		log.info("##图片导入程序开始执行！");	
		super.beginImport();		
		log.info("##图片导入程序执行完毕！");
		log.info("导入结果，成功：" + this.successCount + "# 失败"+ this.errorCount+"个：");
		for (String tmp : this.errors) {
			log.info(tmp);
		}
	}

}
